from django.core.cache import cache
from rest_framework import exceptions

from libs.encrypt import generate_private_and_public_key
from system.models import Encrypt


class EncryptService:
    def get(self):
        return Encrypt.objects.filter(is_deleted=False).first()

    def reset_encrypt_key(self):
        private_key, public_key = generate_private_and_public_key()
        Encrypt.objects.update(is_deleted=True)
        instance = Encrypt.objects.create(
            private_key=private_key,
            public_key=public_key
        )
        k = 'SYSTEM-ENCRYPT-KEY'
        cache.delete(k)
        return instance

    def set_public_key_verify_url(self, public_key_verify_url):
        instance = self.get()
        instance.public_key_verify_url = public_key_verify_url
        instance.save()
        k = 'SYSTEM-ENCRYPT-KEY'
        cache.delete(k)

    def get_encrypt_key(self):
        k = 'SYSTEM-ENCRYPT-KEY'
        v = cache.get(k, None)
        if not v:
            instance = self.get()
            if not instance:
                raise exceptions.ValidationError({'error': '请先初始化加密配置'})
            v = {
                'private_key': instance.private_key,
                'public_key': instance.public_key,
                'public_key_verify_url': instance.public_key_verify_url
            }
            cache.set(k, v, 60*30)
        return v.get('private_key'), v.get('public_key'), v.get('public_key_verify_url')


encrypt_service = EncryptService()
